﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace EventModel
{
    using SqlSugar;
    using System.Configuration;

    public static class SugarBase
    {
        public static string _connString;

        /// <summary>
        /// 
        /// </summary>
        public static SqlSugarClient DB
        {
            get
            {
                return InitDB(30, DbType.MySql, true);
            }
        }

        /// <summary>
        /// 
        /// <returns></returns>
        public static SqlSugarClient GetIntance(int commandTimeOut = 30, DbType dbType = DbType.MySql, bool isAutoCloseConnection = false)
        {
            return InitDB(commandTimeOut, dbType, isAutoCloseConnection);
        }

        /// <summary>
        /// 初始化ORM连接对象
        /// </summary>     
        private static SqlSugarClient InitDB(int commandTimeOut = 30, DbType dbType = DbType.MySql, bool isAutoCloseConnection = false)
        {
            string conn = _connString;
            if (dbType == DbType.MySql)
            {
                conn = _connString;
            }
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conn,
                DbType = dbType,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = isAutoCloseConnection
            });
            db.QueryFilter
            .Add(new SqlFilterItem()
            {
                FilterValue = filterDb =>
                {
                    return new SqlFilterResult() { Sql = " del=0 " };
                },
                IsJoinQuery = false
            }).Add(new SqlFilterItem()
            {
                FilterValue = filterDb =>
                {
                    return new SqlFilterResult() { Sql = " a.del=0 " };
                },
                IsJoinQuery = true
            })
           .Add(new SqlFilterItem()
           {
               FilterName = "query1",
               FilterValue = filterDb =>
               {
                   return new SqlFilterResult() { Sql = " id>@id ", Parameters = new { id = 1 } };
               },
               IsJoinQuery = false
           });

            //Processing prior to execution of SQL
            db.Ado.ProcessingEventStartingSQL = (sql, par) =>
            {
                if (sql.Contains("{0}"))
                {
                    sql = string.Format(sql, "1");
                }
                return new KeyValuePair<string, SugarParameter[]>(sql, par);
            };
            db.Ado.CommandTimeOut = commandTimeOut;
            return db;
        }

        /// <summary>
        /// 执行数据库操作
        /// </summary>
        public static Result Exec<Result>(Func<SqlSugarClient, Result> func, int commandTimeOut = 30, DbType dbType = DbType.MySql)
        {
            if (func == null) throw new Exception("委托为空");
            using (var db = InitDB(commandTimeOut, dbType))
            {
                try
                {
                    db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件，记录要执行的sql语句
                    {

                    };
                    return func(db);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    db.Dispose();
                }
            }
        }

        /// <summary>
        /// 执行数据库操作
        /// </summary>
        public static void Exec(Action<SqlSugarClient> func, int commandTimeOut = 30, DbType dbType = DbType.MySql)
        {
            if (func == null) throw new Exception("委托为空");
            using (var db = InitDB(commandTimeOut, dbType))
            {
                try
                {
                    db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件，记录要执行的sql语句
                    {

                    };
                    func(db);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    db.Dispose();
                }
            }
        }

        /// <summary>
        /// 事务处理
        /// </summary>

        public static Result ExecTran<Result>(Func<SqlSugarClient, Result> func, int commandTimeOut = 30, DbType dbType = DbType.MySql)
        {
            if (func == null) throw new Exception("委托为空");
            using (var db = InitDB(commandTimeOut, dbType))
            {
                try
                {
                    db.Ado.BeginTran(IsolationLevel.Unspecified);
                    var result = func(db);
                    db.Ado.CommitTran();
                    return result;
                }
                catch (Exception ex)
                {
                    db.Ado.RollbackTran();
                    throw ex;
                }
                finally
                {
                    db.Dispose();
                }
            }
        }
    }

}
